using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using cframework;
using Newtonsoft.Json;
namespace cframework
{
    [EssentialTool("zip", "https://github.com/bmatzelle/gow/releases")]
    [CreateAssetMenu(menuName = "cframework/PublishUtil_Standalone_zip")]
    public class PublishUtil_Standalone_zip : PlatformPublishUtil
    {
        static bool BuildStandaloneZip(BuildPlayerSetting setting, string outputProjectPath, string zipFilePath)
        {
            string outputProjectPath2 = outputProjectPath;
            if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.StandaloneOSX)
            {
                outputProjectPath2 += ".app";
            }

            var zipPath = setting.deviceToolPaths.GetCmdToolPath("zip");



            var ret = CommandLineTool.RunCommand2(zipPath, $" -r {zipFilePath} {System.IO.Path.GetFileName(outputProjectPath2)}", System.IO.Path.GetDirectoryName(outputProjectPath));
            if (ret.ExitCode != 0)
            {
                Debug.LogError(ret.StdOut);
                Debug.LogError(ret.StdErr);
                return false;
            }

            return true;
        }

        public override bool BuildAndPublish(BuildPlayerSetting setting, BuildPlayerSetting.PublishInfo publishInfo)
        {
            var zipFilePath = publishInfo.buildOutputPath + $"/{publishInfo.appName}_{setting.platform}_{setting.subPlatform}_{setting.publishType}_{publishInfo.hotupdateVersionNumber}_{publishInfo.timestamp}.zip";

            if (BuildStandaloneZip(setting, publishInfo.outputProjectPath, zipFilePath))
            {
                string downloadUrl = null;
                if (setting.channelUtil.Deploy(setting, $"{zipFilePath}", System.IO.Path.GetFileName(zipFilePath), null, ref downloadUrl))
                {
                    setting.StartHttpServer();

                    Debug.Log("download url: " + downloadUrl);
                    if (EditorUtility.DisplayDialog("play url", downloadUrl, "copy", "ok"))
                    {
                        GUIUtility.systemCopyBuffer = downloadUrl;
                    }
                }
                else
                {
                    EditorUtility.DisplayDialog("deploy failed", "deploy failed", "ok");
                }
            }

            return true;
        }

    }
}